package com.maserb.monitor.web.schoolStudent;

import com.alibaba.fastjson.JSON;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.Role;
import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolTimeTableEntity;
import com.maserb.monitor.enums.SchoolTimeTableDayEnum;
import com.maserb.monitor.enums.SchoolTimeTypeEnum;
import com.maserb.monitor.model.SchoolTimeTableModel;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.schoolStudent.SchoolTimeTableService;
import com.maserb.monitor.service.sysCode.SysCodeService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 课程表后端
 */
@Controller
@RequestMapping("/timeTableBack")
public class SchoolTimeTableBackController {


    @Autowired
    SchoolTimeTableService timeTableService;

    @Autowired
    SysCodeService sysCodeService;

    @Autowired
    JwOrgService orgService;


    @RequestMapping(value = {"/", "/index"})
    public ModelAndView getIndex(final HttpServletRequest request) {
        /*ModelAndView view = new ModelAndView();
        view.setViewName("school_time_table/index");
        SchoolTimeTypeEnum[] timeTypeEnums = SchoolTimeTypeEnum.values();
        SchoolTimeTableDayEnum[] timeTableDayEnums = SchoolTimeTableDayEnum.values();
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = user.getId();
        view.addObject("userId",userId);
        //获取课程
        List<SysCode>codeList = sysCodeService.findByParent("SCHOOL_COURSE");
        view.addObject("timeTypeEnums",timeTypeEnums);
        view.addObject("timeTableDayEnums",timeTableDayEnums);
        view.addObject("codeList",codeList);*/
        ModelAndView view = new ModelAndView();
        view.setViewName("school_time_table/orgList");
        return view;
    }

    @RequestMapping("/getEditTimeTable/{id}")
    public ModelAndView getEditTimeTable(@PathVariable final String id) {
        ModelAndView view = new ModelAndView();
        JwOrgEntity clazz = orgService.findOne(id);
        List<SchoolTimeTableEntity> timeTableEntityList = new ArrayList<SchoolTimeTableEntity>();
        if(null!=clazz){
            timeTableEntityList =  timeTableService.findAll("","","","",id);
        }
        List<SchoolTimeTableModel[]> tableArr = new<SchoolTimeTableModel[]>  ArrayList();
        for(int i=0;i<=6;i++){
            SchoolTimeTableModel[] modelArr = new SchoolTimeTableModel[8];
            for(int j=0;j<=7;j++){
                SchoolTimeTableModel tableModel = new SchoolTimeTableModel();
                modelArr[j]=tableModel;
            }
            tableArr.add(modelArr);
        }
        for(SchoolTimeTableEntity tableEntity:timeTableEntityList){
            int week = Integer.parseInt(tableEntity.getDay())-1;
            int index = tableEntity.getSorts()+(Integer.parseInt(tableEntity.getTimeType())-1)*4-1;
            SchoolTimeTableModel model = new SchoolTimeTableModel();
            if(null!=tableEntity){
                model.setId(tableEntity.getId());
                model.setClazzId(tableEntity.getClazz().getId());
                model.setDay(tableEntity.getDay());
                model.setSorts(tableEntity.getSorts());
                model.setCodeName(tableEntity.getCourse().getName());
            }
            tableArr.get(week)[index] = model;
        }
        view.setViewName("school_time_table/edit_table");
        view.addObject("tableArr", tableArr);
        view.addObject("clazzId",id);
        return view;
    }

    @RequestMapping("/getAdd")
    public ModelAndView getAdd(String clazzId,Integer sorts,Integer day) {
        ModelAndView view = new ModelAndView();
        view.setViewName("school_time_table/add_time_table");
        SchoolTimeTableEntity entity = new SchoolTimeTableEntity();
        JwOrgEntity org = orgService.findOne(clazzId);
        if(sorts>4&&sorts<9){
            entity.setTimeType("2");
            sorts = sorts-4;
        }else if(sorts>8){
            entity.setTimeType("3");
            sorts = sorts-1;
        }else{
            entity.setTimeType("1");
        }
        entity.setSorts(sorts);
        entity.setClazz(org);
        entity.setDay(day.toString());

        //获取课程
        List<SysCode>codeList = sysCodeService.findByParent("SCHOOL_COURSE");
        view.addObject("codeList",codeList);
        view.addObject("entity",entity);
        return view;
    }

    @RequestMapping("/doAdd")
    @ResponseBody
    public AjaxResult<Boolean> doAdd(HttpServletRequest request, SchoolTimeTableEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                if(null==entity.getCourse()||StringUtils.isEmptyOrWhitespace(entity.getCourse().getId())){
                    return false;
                }
                HttpSession session = request.getSession(true);
                UserEntity user = (UserEntity) session.getAttribute("user");
                if(null==user){
                    return false;
                }else{
                    JwOrgEntity org = orgService.findOne(user.getOrgId());
                    if(null!=org){
                        entity.setSchoolId(user.getOrgId());
                        entity.setSchoolName(org.getName());
                    }
                }
                timeTableService.save(entity);
                return true;
            }
        });
    }

    @RequestMapping("/getEdit/{id}")
    public ModelAndView getEdit(@PathVariable final String id) {
        ModelAndView view = new ModelAndView();
        view.setViewName("school_time_table/edit_time_table");
        SchoolTimeTableEntity entity = timeTableService.findOne(id);
        //获取课程
        List<SysCode>codeList = sysCodeService.findByParent("SCHOOL_COURSE");
        view.addObject("codeList",codeList);
        view.addObject("entity",entity);
        return view;
    }

    @RequestMapping("/doUpdate")
    @ResponseBody
    public AjaxResult<Boolean> doUpdate(SchoolTimeTableEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                SchoolTimeTableEntity tableEntity = timeTableService.findOne(entity.getId());
                if(null==entity.getCourse()||StringUtils.isEmptyOrWhitespace(entity.getCourse().getId())){
                    timeTableService.delete(entity.getId());
                    return true;
                }
                tableEntity.setCourse(entity.getCourse());
                timeTableService.save(tableEntity);
                return true;
            }
        });
    }

    /**
    * @Description: 课程列表
    * @Param: [page, timeType, day, courseId, clazzId]
    * @return: com.maserb.monitor.common.PageResponseResult<com.maserb.monitor.entity.schoolStudent.SchoolTimeTableEntity>
    * @Author: Mr.Wang
    * @Date: 2018/8/10
    */
    @RequestMapping("/list")
    @ResponseBody
    public PageResponseResult<SchoolTimeTableEntity> doListSchoolTable(PageRequestParam page,final String userId, final String timeType, final String day,final String courseId,final String clazzId) {
        return AjaxUtils.processPage(page, new Func_T1<Pageable, Page<SchoolTimeTableEntity>>() {
            @Override
            public Page<SchoolTimeTableEntity> invoke(Pageable var1) throws Exception {
                Page<SchoolTimeTableEntity> page = timeTableService.findAll(var1,userId,timeType,day,courseId,clazzId);
                for(SchoolTimeTableEntity entity : page.getContent()){
                    if(!StringUtils.isEmptyOrWhitespace(entity.getTimeType())){
                        entity.setTimeType(SchoolTimeTypeEnum.getNameByValue(Integer.parseInt(entity.getTimeType())));
                    }
                    if(!StringUtils.isEmptyOrWhitespace(entity.getDay())){
                        entity.setDay(SchoolTimeTableDayEnum.getNameByValue(Integer.parseInt(entity.getDay())));
                    }
                    entity.getClazz().setParent(null);
                }
                return page;
            }
        });
    }

    @RequestMapping("/getAddTable")
    public ModelAndView getAddTable() {
        ModelAndView view = new ModelAndView();
        view.setViewName("school_time_table/add");
        SchoolTimeTypeEnum[] timeTypeEnums = SchoolTimeTypeEnum.values();
        SchoolTimeTableDayEnum[] timeTableDayEnums = SchoolTimeTableDayEnum.values();
        //获取课程
        List<SysCode>codeList = sysCodeService.findByParent("SCHOOL_COURSE");
        view.addObject("timeTypeEnums",timeTypeEnums);
        view.addObject("timeTableDayEnums",timeTableDayEnums);
        view.addObject("codeList",codeList);
        return view;
    }

    @RequestMapping("/doAddTable")
    @ResponseBody
    public AjaxResult<Boolean> doAddTable(HttpServletRequest request, SchoolTimeTableEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                HttpSession session = request.getSession(true);
                UserEntity user = (UserEntity) session.getAttribute("user");
                if(null==user){
                   return false;
                }else{
                    JwOrgEntity org = orgService.findOne(user.getOrgId());
                    if(null!=org){
                        entity.setSchoolId(user.getOrgId());
                        entity.setSchoolName(org.getName());
                    }
                }
                timeTableService.save(entity);
                return true;
            }
        });
    }

    @RequestMapping("/getEditTable/{id}")
    public ModelAndView getEditTable(@PathVariable final String id) {
        ModelAndView view = new ModelAndView();
        view.setViewName("school_time_table/edit");
        SchoolTimeTableEntity entity = timeTableService.findOne(id);
        SchoolTimeTypeEnum[] timeTypeEnums = SchoolTimeTypeEnum.values();
        SchoolTimeTableDayEnum[] timeTableDayEnums = SchoolTimeTableDayEnum.values();
        //获取课程
        List<SysCode>codeList = sysCodeService.findByParent("SCHOOL_COURSE");
        view.addObject("timeTypeEnums",timeTypeEnums);
        view.addObject("timeTableDayEnums",timeTableDayEnums);
        view.addObject("codeList",codeList);
        view.addObject("entity",entity);
        return view;
    }

    @RequestMapping("/doUpdateTable")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateTable(SchoolTimeTableEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                SchoolTimeTableEntity tableEntity = timeTableService.findOne(entity.getId());
                tableEntity.setTimeType(entity.getTimeType());
                tableEntity.setDay(entity.getDay());
                tableEntity.setClazz(entity.getClazz());
                tableEntity.setCourse(entity.getCourse());
                tableEntity.setSorts(entity.getSorts());
                timeTableService.save(tableEntity);
                return true;
            }
        });
    }

    @RequestMapping("/doDeleteTable")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteTable(@RequestParam(value = "keys[]") ArrayList<String> keys) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                timeTableService.deleteAllByKeys(keys);
                return true;
            }
        });
    }
}
